#-*- coding:UTF-8 -*-

from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app

from vo.UserInfo import UserInfo
from vo.TaskInfo import TaskInfo
from admin import UserInfoList,AddTask


import datetime
import JsonUtil


'''
登陆接口
用于client每次登陆
'''
class LoginInterface(webapp.RequestHandler):
    
    def get(self):
        imei = None
        macAddress = None
        userInfo = None
        
        try:
            imei = self.request.headers['imei']
            query = UserInfo.all()
            query.filter("imei =", imei)
            userInfo = query.get()
        except:
            pass
        
        if userInfo is None:
            try:
                macAddress = self.request.headers['mac_address']
                query = UserInfo.all()
                query.filter("macAddress =", macAddress)
                userInfo = query.get()
            except:
                pass
        
        if userInfo is None:
            userInfo = UserInfo()
            
        try:
            userInfo.imei = self.request.headers['imei']
        except:
            pass
        try:
            userInfo.imsi = self.request.headers['imsi']
        except:
            pass
        try:
            userInfo.macAddress = self.request.headers['mac_address']
        except:
            pass
        try:
            userInfo.latitude = self.request.headers['latitude']
        except:
            pass
        try:
            userInfo.longitude = self.request.headers['longitude']
        except:
            pass
        try:
            userInfo.deviceName = self.request.headers['device_name']
        except:
            pass
        try:
            userInfo.appName = unicode(self.request.headers['app_name'],'utf-8')
        except:
            pass
        try:
            userInfo.appPKG = self.request.headers['app_pkg']
        except:
            pass
        
        if userInfo.loginCount is None:
            userInfo.loginCount = 1
        else:
            userInfo.loginCount = userInfo.loginCount + 1
        
        userInfo.createDate = datetime.datetime.utcnow()
        
        userInfo.save()
        
        self.response.headers['result'] = 'success'
        

'''
任务查询列表
'''
class TaskListInterface(webapp.RequestHandler):
    def get(self):
        query = TaskInfo.gql('');
        self.response.out.write(JsonUtil.encode(query))


application = webapp.WSGIApplication([('/login', LoginInterface)
                                      , ('/tasklist', TaskListInterface)
                                      , ('/admin', UserInfoList)
                                      , ('/addtask', AddTask)], debug=True)


def main():
    run_wsgi_app(application)

if __name__ == "__main__":
    main()
